package com.tanhua.dubbo.api;

import com.tanhua.model.domain.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author lk
 * @date 2022-04-03
 */
@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询看过我的人
    @Override
    public List<Visitors> queryMyVisitor(Long userId, Long data) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (data != null) {
            //将上次查看之前的访问记录排除
            criteria.and("date").lt(data);
        }
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("data")));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    //保存访问信息
    @Override
    public void saveVisitor(Visitors visitors) {
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        if (!exists) {
            //不存在则保存
            mongoTemplate.save(visitors);
        }
    }
}
